using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Forms; // for SendKeys
using System.Windows.Input;
using DesktopHelper.Data;
using DesktopHelper.Models;
using DesktopHelper.Services;

namespace DesktopHelper.Views
{
    public partial class ClipboardHistoryWindow : Window
    {
        private readonly DatabaseService _databaseService;
        private readonly ClipboardService _clipboardService;
        public ObservableCollection<ClipboardItemDisplay> HistoryItems { get; set; }

        public ClipboardHistoryWindow()
        {
            InitializeComponent();
            
            // 从App获取服务
            var app = (App)System.Windows.Application.Current;
            _databaseService = app.Host?.Services.GetRequiredService<DatabaseService>() 
                               ?? throw new InvalidOperationException("无法获取数据库服务");
            _clipboardService = app.Host?.Services.GetRequiredService<ClipboardService>() 
                               ?? throw new InvalidOperationException("无法获取剪贴板服务");
            
            HistoryItems = new ObservableCollection<ClipboardItemDisplay>();
            HistoryListBox.ItemsSource = HistoryItems;
            
            // 订阅剪贴板事件
            _clipboardService.ClipboardItemAdded += OnClipboardItemAdded;
            
            // 窗口加载后设置焦点
            Loaded += (s, e) =>
            {
                HistoryListBox.Focus();
                if (HistoryItems.Count > 0)
                {
                    HistoryListBox.SelectedIndex = 0;
                }
            };
            
            LoadHistoryItems();
        }

        private async void LoadHistoryItems()
        {
            try
            {
                var items = await _databaseService.GetClipboardHistoryAsync(20); // 获取最近20条记录
                
                HistoryItems.Clear();
                foreach (var item in items.OrderByDescending(x => x.CreateTime))
                {
                    HistoryItems.Add(new ClipboardItemDisplay
                    {
                        Id = item.Id,
                        Type = GetTypeDisplayName(item.Type),
                        DisplayContent = GetDisplayContent(item),
                        CreateTime = item.CreateTime,
                        OriginalItem = item
                    });
                }
                
                // 显示/隐藏空状态提示
                EmptyStateText.Visibility = HistoryItems.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"加载剪贴板历史失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private string GetTypeDisplayName(ClipboardDataType type)
        {
            return type switch
            {
                ClipboardDataType.Text => "文本",
                ClipboardDataType.Image => "图片",
                ClipboardDataType.File => "文件",
                _ => "未知"
            };
        }

        private string GetDisplayContent(ClipboardItem item)
        {
            return item.Type switch
            {
                ClipboardDataType.Text => item.Content ?? "",
                ClipboardDataType.Image => "[图片]",
                ClipboardDataType.File => $"[文件] {item.Content}",
                _ => "[未知类型]"
            };
        }

        private async void HistoryListBox_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (HistoryListBox.SelectedItem is ClipboardItemDisplay selectedItem)
            {
                Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 双击选中项目: {selectedItem.Type} - {selectedItem.DisplayContent}");
                await PasteClipboardItem(selectedItem.OriginalItem);
                if (!IsClosing)
                {
                    Close();
                }
            }
        }

        private async System.Threading.Tasks.Task PasteClipboardItem(ClipboardItem item)
        {
            try
            {
                Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 开始粘贴项目: {item.Type}");
                
                switch (item.Type)
                {
                    case ClipboardDataType.Text:
                        if (!string.IsNullOrEmpty(item.Content))
                        {
                            Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 设置文本到剪贴板: {item.Content.Substring(0, Math.Min(50, item.Content.Length))}...");
                            System.Windows.Clipboard.SetText(item.Content);
                            
                            // 等待剪贴板设置完成
                            await System.Threading.Tasks.Task.Delay(100);
                            
                            // 隐藏窗口先，然后模拟粘贴
                            WindowState = WindowState.Minimized;
                            Hide();
                            await System.Threading.Tasks.Task.Delay(50);
                            
                            Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 正在模拟 Ctrl+V 粘贴...");
                            System.Windows.Forms.SendKeys.SendWait("^v");
                            Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 文本粘贴完成");
                        }
                        break;
                        
                    case ClipboardDataType.Image:
                        if (item.ImageData != null && item.ImageData.Length > 0)
                        {
                            Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 设置图片到剪贴板...");
                            var image = ImageFromBytes(item.ImageData);
                            if (image != null)
                            {
                                System.Windows.Clipboard.SetImage(image);
                                await System.Threading.Tasks.Task.Delay(100);
                                
                                WindowState = WindowState.Minimized;
                                Hide();
                                await System.Threading.Tasks.Task.Delay(50);
                                
                                Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 正在模拟 Ctrl+V 粘贴图片...");
                                System.Windows.Forms.SendKeys.SendWait("^v");
                                Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 图片粘贴完成");
                            }
                        }
                        break;
                        
                    case ClipboardDataType.File:
                        if (!string.IsNullOrEmpty(item.Content))
                        {
                            Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 设置文件到剪贴板: {item.Content}");
                            var files = item.Content.Split(';', StringSplitOptions.RemoveEmptyEntries);
                            var fileList = new System.Collections.Specialized.StringCollection();
                            foreach (var file in files)
                            {
                                if (System.IO.File.Exists(file) || System.IO.Directory.Exists(file))
                                {
                                    fileList.Add(file);
                                }
                            }
                            
                            if (fileList.Count > 0)
                            {
                                System.Windows.Clipboard.SetFileDropList(fileList);
                                await System.Threading.Tasks.Task.Delay(100);
                                
                                WindowState = WindowState.Minimized;
                                Hide();
                                await System.Threading.Tasks.Task.Delay(50);
                                
                                Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 正在模拟 Ctrl+V 粘贴文件...");
                                System.Windows.Forms.SendKeys.SendWait("^v");
                                Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 文件粘贴完成");
                            }
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 粘贴失败: {ex.Message}");
                System.Windows.MessageBox.Show($"粘贴失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private System.Windows.Media.Imaging.BitmapSource? ImageFromBytes(byte[] imageData)
        {
            try
            {
                using var stream = new System.IO.MemoryStream(imageData);
                var decoder = System.Windows.Media.Imaging.BitmapDecoder.Create(
                    stream, 
                    System.Windows.Media.Imaging.BitmapCreateOptions.None, 
                    System.Windows.Media.Imaging.BitmapCacheOption.OnLoad);
                return decoder.Frames[0];
            }
            catch
            {
                return null;
            }
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            if (!IsClosing)
            {
                Close();
            }
        }

        private void Window_Deactivated(object sender, EventArgs e)
        {
            // 窗口失去焦点时自动关闭
            // 使用Dispatcher.BeginInvoke延迟执行，避免在窗口关闭期间调用Close
            Dispatcher.BeginInvoke(new Action(() =>
            {
                try
                {
                    if (!IsClosing)
                    {
                        Close();
                    }
                }
                catch (InvalidOperationException)
                {
                    // 忽略窗口关闭期间的异常
                }
            }), System.Windows.Threading.DispatcherPriority.Background);
        }

        private bool IsClosing { get; set; }

        private void OnClipboardItemAdded(object? sender, ClipboardItem item)
        {
            // 在UI线程上更新界面
            Dispatcher.Invoke(() =>
            {
                var displayItem = new ClipboardItemDisplay
                {
                    Id = item.Id,
                    Type = GetTypeDisplayName(item.Type),
                    DisplayContent = GetDisplayContent(item),
                    CreateTime = item.CreateTime,
                    OriginalItem = item
                };
                
                // 在列表顶部插入新项目
                HistoryItems.Insert(0, displayItem);
                
                // 保持最多20个项目
                while (HistoryItems.Count > 20)
                {
                    HistoryItems.RemoveAt(HistoryItems.Count - 1);
                }
                
                // 隐藏空状态提示
                EmptyStateText.Visibility = Visibility.Collapsed;
            });
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            IsClosing = true;
            base.OnClosing(e);
        }

        protected override void OnClosed(EventArgs e)
        {
            // 取消订阅事件
            _clipboardService.ClipboardItemAdded -= OnClipboardItemAdded;
            base.OnClosed(e);
        }

        protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e)
        {
            // ESC键关闭窗口
            if (e.Key == Key.Escape && !IsClosing)
            {
                Close();
            }
            // Enter键粘贴选中的项目
            else if (e.Key == Key.Enter && HistoryListBox.SelectedItem is ClipboardItemDisplay selectedItem)
            {
                Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] 按下Enter键粘贴项目");
                _ = PasteClipboardItem(selectedItem.OriginalItem);
                if (!IsClosing)
                {
                    Close();
                }
            }
            base.OnKeyDown(e);
        }
    }

    // 显示用的数据模型
    public class ClipboardItemDisplay
    {
        public int Id { get; set; }
        public string Type { get; set; } = "";
        public string DisplayContent { get; set; } = "";
        public DateTime CreateTime { get; set; }
        public ClipboardItem OriginalItem { get; set; } = null!;
    }
}